<?php
function cache_get_user($u,$con=true){
	$c=new cache;
	if($con){
	$dt=$c->load($u,"user");
	}
	if(!$dt){
	 $db=new db;
	 $db->connect();
	 $db->query("select * from users where username='".$u."'");
	 $db->close();
	 
		if($db->num_rows()>0){
			$dt=$db->fetchOne();	
			
			 if($dt['avatar']!=""){
                 $ava=explode("_",$dt['avatar']);
 				 $dt['avatar']=AVATAR."100/".$ava[0]."/".$ava['1']."/".$ava['2']."/".$dt['avatar'];
 		   }else
		   if($dt['facebook']==1){
			       $dt['avatar']="https://graph.facebook.com/".$dt['facebook_id']."/picture";
				   $dt['lavatar']="https://graph.facebook.com/".$dt['facebook_id']."/picture?type=large";
           
			}else{
				$dt['avatar']=AVATAR_DEFAULT;
			}
			
			$db2=new db;
			$db2->connect();
			 //GET POST,VIEW , LIKE , COMMENT ------
			 $sql="select sum(views) as views,sum(likes) as likes,sum(comments) as comments,count(*) as post from index_post where username='".$u."'";
			 $db2->query($sql);
			
			 $num=$db2->fetchOne();
				
			
			$db2->close();	
			
			
			 $dt['comments']=$num['comments'];
			 $dt['likes']=$num['likes'];
			 $dt['views']=$num['views'];
			 $dt['posts']=$num['post'];
			 $dt['albums']=cache_get_album_num_user($u);
			 
			
			
			
			$c->save($u,$dt,300000,"user");
			return $dt;
		}else{
			return false;
		}
	}
	return $dt;
	

}

function get_post($id){
		$db=new db;
		$db->connect();
		$db->query("select * from index_post where id=".$id);
		$dt=$db->fetchOne();
		if($dt['is_image']==1){
			$tb='post_image';
			}
			if($dt['is_video']==1){
			$tb='post_media';
			}
			if($dt['is_text']==1){
			$tb='post_text';
			}
			
			return cache_get_post($dt['post_id'],$tb,$id);
	}

function cache_get_post($id,$table="post_image",$pid=''){
	
	$c=new cache;
	$dt=$c->load($pid,"post/".$table);
	if(!$dt){
	
		 $sql="select n.*,c.name as cat_name,c.id as cat_id,c.alias from ".$table." as n left join category as c
		 on c.id=n.cat_id
		 where n.id=".$id;
		 $db=new db;
		 $db->connect();
		 $db->query($sql);
		 
		 if($db->num_rows()>0){
			 $dt=$db->fetchOne();
			 $dt['pid']=$pid;
			 
			 //FACEBOOK QUERY GET STATIC -----------------
			 $url=HOME.'index.php?module=news&act=view&id='.$pid;
			 $fb=get_facebook_info($url);
			 $db->nonquery('update index_post set comments='.$fb['comment'].',likes='.$fb['like'].' where id='.$id);	
			 
			 $dt['likes']=$fb['like'];
			 $dt['comments']=$fb['comment'];
			 //End of facebok update sql query-----		 
			 
			 
			 switch($table){
			 case "post_image":
			
			 	$dt['type']='image';
			 	$im = explode('_', $dt['image']);
				$im2=$im[0]."/".$im[1]."/".$im[2]."/".$dt['image'];
				
				$gifext=strtolower(substr($dt['image'],-3,3));
				if($gifext=='gif'){
					$dt['image_gif']=1;
					$image_big="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_ORIGINAL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
					$image_med="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_ORIGINAL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
					$image_small="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_ORIGINAL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
				}else{
					$dt['image_gif']=0;
					$image_big="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_BIG."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
					$image_med="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_MED."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
					$image_small="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_SMALL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
				}
				
				$dt['image'] =IMAGE_URL.IMAGE_PICTURE.IMAGE_BIG."/".$im2;
				$dt['image_big'] = IMAGE_URL.IMAGE_PICTURE.IMAGE_BIG."/".$im2;
				$dt['image_near_big'] = IMAGE_URL.IMAGE_PICTURE.IMAGE_NEAR_BIG."/".$im2;
				$dt['image_med'] =IMAGE_URL.IMAGE_PICTURE.IMAGE_MED."/".$im2;
				$dt['image_small'] =IMAGE_URL.IMAGE_PICTURE.IMAGE_SMALL."/".$im2;
			
			
				 //$image_val="<img src='".$dt['image']."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
				//GET SOURCE IMAGE
						$db->query("select * from  images where post_id=".$dt['id']);
						if($db->num_rows()>0){
								$link=$db->fetchAll();

								foreach($link as $val){
								$im = explode('_', $val['image']);
								$im2=$im[0]."/".$im[1]."/".$im[2]."/".$val['image'];
								
								$gifext=strtolower(substr($val['image'],-3,3));
									if($gifext=='gif'){
										$image_big.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_ORIGINAL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
										$image_near_big.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_ORIGINAL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
										
										$image_med.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_ORIGINAL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
										$image_small.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_ORIGINAL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
									}else{
										$image_big.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_BIG."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
										$image_near_big.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_NEAR_BIG."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
										
										$image_med.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_MED."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
										$image_small.="<img src='".IMAGE_URL.IMAGE_PICTURE.IMAGE_SMALL."/".$im2."' class='img-rounded img-responsive' style='margin:auto' /><br/>";
									}
								}
							}
							
				$dt['images_big'] = $image_big;
				$dt['images_near_big'] = $image_near_big;
				$dt['images_small'] = $image_small;
				$dt['images_med'] = $image_med;
				
				break;
			 case "post_text":
				$dt['type']='text';
			 	$im = explode('_', $dt['image']);
				$im2=$im[0]."/".$im[1]."/".$im[2]."/".$dt['image'];
				$dt['image'] =IMAGE_URL.IMAGE_TEXT.IMAGE_BIG."/".$im2;
				$dt['image_big'] = IMAGE_URL.IMAGE_TEXT.IMAGE_BIG."/".$im2;
				$dt['image_near_big'] = IMAGE_URL.IMAGE_TEXT.IMAGE_NEAR_BIG."/".$im2;
				$dt['image_med'] =IMAGE_URL.IMAGE_TEXT.IMAGE_MED."/".$im2;
				$dt['image_small'] =IMAGE_URL.IMAGE_TEXT.IMAGE_SMALL."/".$im2;
				
				break;	
			  case "post_media":
			    $dt['type']='video';
			  try{
			 	$u=videofactory::create($dt['media_type']);
				$u->setLink($dt['url']);
				$param=$u->getQueryParams();
				if($param['list']){
					$u->setEmbedCode($param, true);
				}else{
					$u->setEmbedCode($param);
				}
				$dt['embed'] = $u->getEmbedCode();
								
				$dt['image'] ="http://img.youtube.com/vi/".$param['v']."/0.jpg";
				$dt['image_big'] ="http://img.youtube.com/vi/".$param['v']."/0.jpg";
				$dt['image_med'] ="http://img.youtube.com/vi/".$param['v']."/0.jpg";
				$dt['image_near_big'] ="http://img.youtube.com/vi/".$param['v']."/0.jpg";
				$dt['image_small'] ="http://img.youtube.com/vi/".$param['v']."/2.jpg";
				
				}catch (Exception $e){
				
				}
				
				break;
			  
			 }
				
			 
			 $dt['likes'] = k_format($dt['likes']);
			 $dt['comments'] = k_format($dt['comments']);
			 $dt['views'] = k_format($dt['views']);
			 $dt['date_created'] = time_ago($dt['date_created']);
			 
			 $db->close();
			 $c->save($pid,$dt,3600,"post/".$table);
			 return $dt;
		 }else{
		  	$db->close();
			return false;
		 }
	}
	return $dt;

}


function cache_get_album($id){
	
	$c=new cache;
	$dt=$c->load($id,"album");
	if(!$dt){
		 $sql="select * from album where id=".$id;
		 $db=new db;
		 $db->connect();
		 $db->query($sql);
		 
		 if($db->num_rows()>0){
			 $dt=$db->fetchOne();
			 
			 //GET POST,VIEW , LIKE , COMMENT ------
			 $db->query("select sum(views) as views,sum(likes) as likes,sum(comments) as comments,count(*) as post from index_post where id_album=".$id);
			 $num=$db->fetchOne();
			 $dt['image']=album_get_image($id);
			 $dt['comments']=$num['comments'];
			 $dt['likes']=$num['likes'];
			 $dt['views']=$num['views'];
			 $dt['posts']=$num['post'];
			
			 $dt['list_item']=album_get_list_item($dt['id']);
			 $db->nonquery("update album set comments=".$num['comments'].",likes=".$num['likes'].",views=".$num['views']." where id=".$id);
			 
			 // GET LIST ITEM IN THIS ALBUM -------
			 
			 //-----------
			 $db->close();
			 $c->save($id,$dt,300000,"album");
			 return $dt;
		 }else{
		  	$db->close();
			return false;
		 }
	}
	return $dt;

}


function album_get_image($id){
	$db=new db;
	$db->connect();
	$db->query('select id from index_post where id_album='.$id.' order by id asc limit 0,1');
	if($db->num_rows()>0){
		$row=$db->fetchOne();
		$rdt=get_post($row['id']);
		return $rdt['image'];
	}
	return IMAGE_DEFAULT_ALBUM;
}


function album_get_list_item($id){
    $db=new db;
	$db->connect();
	$db->query('select id from index_post where id_album='.$id.' order by id desc limit 0,6');
	if($db->num_rows()>0){
		$dt=$db->fetchAll();
		$data= array();
		foreach($dt as $row){
			$post=get_post($row['id']);
			$post2['image']=$post['image'];
			$post2['image_small']=$post['image_small'];
			$post2['title']=$post['title'];
			$post2['id']=$row['id'];
			$data[]=$post2;
		}
		return $data;
	}else{
	return false;	
		}
}

function cache_get_category($id){
	$cache=new cache;
	$dt=$cache->load('category'.$id,'category');
	if(!$dt){
		$db=new db;
		$db->connect();
		$db->query('select * from category where id='.$id);
		$dt=$db->fetchOne();
		$cache->save('category'.$id,$dt,3600,'category');
	}
	return $dt;
	
	}

function cache_get_album_num_user($username){
	$db=new db;
	$db->connect();
	$db->query("select count(*) as num from album where username='".$username."'");
	$dt=$db->fetchOne();
	$db->close();
	return $dt['num'];
}
	
function cache_get_modal_array($id,$type='',$ref=true){
	//Tinh den xu ly truong hop default, khi user duoc send link tren facebook, thi xu ly cho user o trang chu luon, nhung ko co session page, session query, session tpage, chi co id bai viet 
	//Truong hop nay minh se set default cho user load quickview se la id dau tien cua page 1
	if($ref==false){
		//Lay du lieu va luu vao cache cho thang nay
		$_SESSION['load']['query']='';
		$_SESSION['load']['tpage']='';
		$_SESSION['load']['page']='';
	}
	
	
	$cache=new cache;
	$page=$_SESSION['load']['page'];
	
	if($page==$_SESSION['load']['tpage']){
		$lpage=true;
	}else{
		$lpage=false;
	}
	
	if($page==1){
		$fpage=true;
	}else{
		$fpage=false;
	}
	
	$query= $_SESSION['load']['query']." limit ".(($page-1)*LOAD_ITEMS).",".LOAD_ITEMS;
	
	$dt=$cache->load($query,'pagination');
	if(!$dt){
		$db = new db;
		$db->connect();
		$db->query($query);
		$dt=$db->fetchAll();
		
		//-----
			$data3=array();
			$i=0;
			foreach($dt as $row)
					{
						
							if($row['is_image']==1){
									$data3[]=cache_get_post($row['post_id'],"post_image",$row['id']);
								
							}
							
							if($row['is_video']==1){
								$data3[]=cache_get_post($row['post_id'],"post_media",$row['id']);
							}
							
							if($row['is_text']==1){
								$data3[]=cache_get_post($row['post_id'],"post_text",$row['id']);
							
							}
							
					
						
					}
		
		//-----
		$dt=$data3;

		$cache->save($query,$data3,360,'pagination');
	}
	
	$keyitem='';
	
 
	
	//Lưu ý, có 2 trường hợp, nếu type='1', thi se lay du lieu la gia tri dau tien cua mang
									// type='2' thi se lay gia tri cuoi cung cua mang
									
		if($type==2){
			$data=$dt[0];
			return $data;
		}
		if($type==1){
			$num=count($dt);
			$data=$dt[$num-1];
			return $data;
		}
	
	$max_num=count($dt);

	//Phai chu i, tim thay key o phan tu cuoi cung cua mang ----------
	foreach($dt as $key=>$value){
		
		
		if($value['pid']==$id){
			if($_GET['nav'] == 'preNav'){
				
					if($key==0){
						//ID LA BAI VIET CUOI CUNG CUA MANG, PHAI QUA MANG KHAC
						if($fpage){
							//$error_min_page = true;
							return array('error_min_page'=>true);
						}else{
							//Tang session page len
							$_SESSION['load']['page'] = $_SESSION['load']['page'] - 1;
							//echo 'here - ' . $_SESSION['load']['page'];
							//Load value la cuoi cung cua mang tiep theo -----
							$data=cache_get_modal_array($id,1);
							return $data;
						}
					}else{
					$keyitem = $key - 1;
					break;
				
				
				
				
					
					}
					
				}else{ // else $_GET['nav'] == 'preNav'
				
				if(($key+1)==$max_num){
						//ID LA BAI VIET CUOI CUNG CUA MANG, PHAI QUA MANG KHAC
						if($lpage){
							//Return la da het du lieu roi , het page ^^
							return array('error_max_page'=>true);
							return false;
						}else{
							//Tang session page len
							$_SESSION['load']['page']=$_SESSION['load']['page']+1;
							//echo 'here + ' . $_SESSION['load']['page'];
							//Load value la id dau tien cua mang tiep theo -----
							$data=cache_get_modal_array($id,2);
							return $data;
						}
					}else{
						$keyitem = $key + 1;
						break;
				
				
					}
				} //end of else  $_GET['nav'] == 'preNav'
		} //end of $value['pid']==$id
		
		// DA TIM DUOC KEYITEM, RETURN DATA
		
	
		
	} // End of foreach

		return $dt[$keyitem];

}